<?php
require_once 'config.php';
require_once 'db_manager.php';
require_once 'carrier_map.php';
session_start();

// 检查是否已登录
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// 处理删除请求
if (isset($_GET['delete'])) {
    $db = DBManager::getInstance();
    $conn = $db->getConnection();
    $stmt = $conn->prepare("DELETE FROM tracking_history WHERE id = ? AND name = ?");
    $stmt->bind_param("is", $_GET['delete'], $_SESSION['username']);
    $stmt->execute();
    $stmt->close();
    
    header("Location: history.php");
    exit();
}

// 获取查询历史
$db = DBManager::getInstance();
$conn = $db->getConnection();

// 添加搜索功能
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$where_clause = "WHERE name = ?";
$params = [$_SESSION['username']];
$types = "s";

if (!empty($search)) {
    $where_clause .= " AND tracking_number LIKE ?";
    $search_param = "%" . $search . "%";
    $params[] = $search_param;
    $types .= "s";
}

$stmt = $conn->prepare("SELECT * FROM tracking_history $where_clause ORDER BY query_time DESC");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<?php include 'header.php'; ?>

<div class="container" style="max-width:900px;">
    <div class="main-card">
        <h2 class="express-search-title">查询历史</h2>
        
        <!-- 添加搜索框 -->
        <form method="GET" class="mb-4">
            <div class="input-group">
                <input type="text" name="search" class="form-control" placeholder="输入快递单号搜索..." value="<?php echo htmlspecialchars($search); ?>">
                <div class="input-group-append">
                    <button class="btn btn-primary" type="submit">搜索</button>
                    <?php if (!empty($search)): ?>
                        <a href="history.php" class="btn btn-secondary">清除</a>
                    <?php endif; ?>
                </div>
            </div>
        </form>

        <?php if(empty($history)): ?>
            <div class="alert alert-info">暂无查询记录</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>单号</th>
                            <th>快递公司</th>
                            <th>快递状态</th>
                            <th>快递信息</th>
                            <th class="query-time-col">查询时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $unique_history = array();
                        foreach($history as $item) {
                            $tracking_number = explode(':', $item['tracking_number'])[0];
                            if (!isset($unique_history[$tracking_number])) {
                                $unique_history[$tracking_number] = $item;
                            }
                        }
                        foreach($unique_history as $item): 
                            $carrier_name = '';
                            if (!empty($item['carrier'])) {
                                $carrier_code = strtolower($item['carrier']);
                                $carrier_name = isset($carrier_map[$carrier_code]) ? $carrier_map[$carrier_code] : $item['carrier'];
                            }
                        ?>
                            <tr onclick="window.location.href='index.php?tracking_number=<?php echo $item['tracking_number']; ?><?php if(!empty($item['carrier'])) echo '&carrier=' . urlencode($item['carrier']); ?>'">
                                <td><?php echo explode(':', $item['tracking_number'])[0]; ?></td>
                                <td><?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?></td>
                                <td><?php echo !empty($item['express_status']) ? htmlspecialchars($item['express_status']) : '未知'; ?></td>
                                <td class="history-status">
                                    <?php 
                                    $status = isset($item['status']) ? (string)$item['status'] : '暂无状态';
                                    if (mb_strlen($status, 'UTF-8') > 20) {
                                        echo mb_substr($status, 0, 20, 'UTF-8') . '...';
                                    } else {
                                        echo $status;
                                    }
                                    ?>
                                </td>
                                <td class="query-time-col"><?php echo $item['query_time']; ?></td>
                                <td>
                                    <a href="history.php?delete=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要删除这条记录吗？')">删除</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.table th.query-time-col, .table td.query-time-col {
    min-width: 140px;
    white-space: nowrap;
}
</style>

<?php include 'footer.php'; ?> 